package com.yugao.fintech.framework.assistant.core.jar;

import cn.hutool.core.io.FileUtil;
import com.google.common.io.Files;
import com.yugao.fintech.framework.assistant.core.OSInfo;
import com.yugao.fintech.framework.assistant.core.UrlUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 本地方式运行jar, 没有打包成jar
 */
public class JarBuildByLocalRun extends JarBuildWay {
    /**
     * 资源根目录
     */
    private final List<String> resourcePaths = new ArrayList<>();

    public JarBuildByLocalRun(CopyResourcesInfo copyResourcesInfo) {
        super(copyResourcesInfo);
        Class<?> aClass = copyResourcesInfo.getResourcesInfo().getClass();
        URL resourceUrl = aClass.getResource("/");
        if (resourceUrl == null) {
            throw new RuntimeException("aClass.getResource(\"\") == null");
        }
        // 变成
        String resourceRootPath = resourceUrl.getPath().replace("/", File.separator);
        if (OSInfo.isWindows()) {
            resourceRootPath = resourceRootPath.substring(1);
        }

        ResourcesInfo resourcesInfo = copyResourcesInfo.getResourcesInfo();
        if (resourcesInfo.classPaths() != null) {
            for (String classPath : resourcesInfo.classPaths()) {
                resourcePaths.add(resourceRootPath + classPath.replace("/", File.separator));
            }
        }

        // 设置当前jarName名称 (因为在本地运行, 没有jar包)
        this.jarName = "";
    }

    @Override
    protected void doCopyResourcesToLocal() throws IOException {
        for (String resourcePath : resourcePaths) {
            List<File> allResourceFile = FileUtil.loopFiles(resourcePath);
            for (File resourceFile : allResourceFile) {
                // 如果填入的资源路径是空, 这里就只拷贝 resource下的资源, 不拷贝源码
                if (resourceFile.getPath().endsWith(".class")) {
                    continue;
                }
                String fileClassPath = resourceFile.getPath()
                        .replace(UrlUtils.removeEndSlash(resourcePath) + File.separator, "");
                JarResourcesFile jarResourcesFile = new JarResourcesFile(fileClassPath, jarName, resourcePath);
                if (copyAfterCallback != null && copyAfterCallback.apply(jarResourcesFile)) {
                    TargetFile targetFile = new TargetFile(jarResourcesFile.getClassPath(), copyResourcesInfo);
                    Files.copy(resourceFile, new File(targetFile.getDirPath() + File.separator + targetFile.getClassPath()));
                }
            }
        }
    }
}
